package framework.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletException;

/**
 * 使用 netty 作为 servlet服务器
 *
 * @author ME
 */
public class WebServer {
    private static Logger logger = LoggerFactory.getLogger(WebServer.class);

    /**
     * http://127.0.0.1:6001/user/login?username=ljy&pwd=12345
     *
     * @param args
     */
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(WebServer.class);
        Integer port = 6001;
        DispatcherServlet servlet = getDispatcherServlet(ctx);
        NettyHttpServer server = new NettyHttpServer(port, servlet);
        server.start();
    }

    /**
     * 此处配置 dispatcher-servlet 子容器（spring-servlet.xml）
     *
     * @return
     */
    public static DispatcherServlet getDispatcherServlet(ApplicationContext ctx) {
        XmlWebApplicationContext mvcContext = new XmlWebApplicationContext();
        mvcContext.setConfigLocation("classpath:framework/netty/spring-servlet.xml");
        mvcContext.setParent(ctx);

        // AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
        // // 可以直接注册 Java-based 配置类
        // mvcContext.register(NettyConfig.class);
        //
        // // 也可以通过 setConfigLocation 指定 Java-based 配置类全路径
        // mvcContext.setConfigLocation("framework.netty.NettyConfig");
        // mvcContext.setParent(ctx);

        MockServletConfig servletConfig = new MockServletConfig(mvcContext.getServletContext(), "dispatcherServlet");
        DispatcherServlet dispatcherServlet = new DispatcherServlet(mvcContext);
        try {
            dispatcherServlet.init(servletConfig);
        } catch (ServletException e) {
            e.printStackTrace();
        }
        return dispatcherServlet;
    }

}
